package com.siyoumi.app.modules.sh.web;

import com.alibaba.fastjson.JSONObject;
import com.siyoumi.controller.ApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XHttpClient;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/e/ccbact/m01/index.html")
public class ApiCcbIndex
        extends ApiController {
    @SneakyThrows
    @GetMapping("")
    public XReturn index() {
        String wParam = input("wParam");
        if (XStr.isNullOrEmpty(wParam)) {
            return EnumSys.MISS_VAL.getR("miss wParam");
        }

        XReturn r = getZhcToken(wParam);
        if (r.err()) {
            return r;
        }

        String uuid = r.getData("uuid");
        //更新uuid
        getR().setData("uuid", uuid);

        return getR();
    }


    public XReturn getZhcToken(String wParam) {
        String url = "https://event.ccbft.com/api/flow/nf/shortLink/redirect/ccb_gjb";
        Map<String, Object> postData = new HashMap<>();
        postData.put("appId", "wxd513efdbf26b5744");
        postData.put("archId", "ccb_gjb");
        postData.put("channelId", "wx");
        postData.put("shortId", "polFsWD2jPnjhOx9ruVBcA");
        postData.put("ifWxFirst", true);
        postData.put("wParam", wParam);

        XHttpClient client = XHttpClient.getInstance();
        String returnStr = client.postJson(url, null, postData);
        XReturn r = XReturn.parse(returnStr);
        if (r.err()) {
            return r;
        }

        JSONObject data = (JSONObject) r.get("data");
        String uuid = data.getString("wxUUID");
        r.setData("uuid", uuid);

        return r;
    }
}
